package com.chujian.framework.ws.support.srv;


import com.chujian.framework.ws.WsConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.WebSocketSession;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class WsContext {

    /**
     * Session保持 客户端ID -> session
     */
    private static final ConcurrentHashMap<String, WebSocketSession> sessionKeeper = new ConcurrentHashMap<>();

    /**
     * session 数量
     */
    private static final AtomicInteger sessionCount = new AtomicInteger();

    public static void addSession(WebSocketSession session) {
        String cliId = getCliId(session);
        sessionKeeper.put(cliId, session);

        int count = WsContext.sessionCount.incrementAndGet();

        log.info("客户端 {} 建立连接，现有连接数: {}", cliId, count);
    }

    public static void removeSession(WebSocketSession session) {
        String cliId = getCliId(session);
        sessionKeeper.remove(cliId);

        int count = WsContext.sessionCount.decrementAndGet();

        log.info("客户端 {} 断开连接，现有连接数: {}", cliId, count);
    }

    /**
     * 获取连接客户端标识
     *
     * @param session
     * @return
     */
    public static String getCliId(WebSocketSession session) {
        Map<String, Object> attributes = session.getAttributes();
        return (String) attributes.get(WsConst.SESSION_CLI_ID);
    }


    public static WebSocketSession getSession(String code) {
        return sessionKeeper.get(code);
    }


}
